package com.xdkj.es.util;

import com.xdkj.es.entiti.JDGoods;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * @author joke
 * @version 1.0
 * @date 2021/12/19-18:45
 */
@Component
public class HtmlParseUtil {
    public List<JDGoods> JDSearch(String keyword) throws Exception {
        //拼接url
        String url = "https://search.jd.com/Search?keyword=" + keyword + "&enc=utf-8";
        //进行url请求，请求网页
        Document document = Jsoup.parse(new URL(url), 3000);
        //获取 所有 商品对应的dom元素
        Element j_goodsList = document.getElementById("J_goodsList");
        //获取 每个 商品对应的dom元素
        Elements li = j_goodsList.getElementsByTag("li");
        //将所获取的信息放入list中
        ArrayList<JDGoods> jdGoods = new ArrayList<>();
        // 遍历将数据存入list
        for (Element item : li) {
            String img = item.getElementsByTag("img").eq(0).attr("data-lazy-img");
            System.out.println(img);
            String title = item.getElementsByClass("p-name").eq(0).text();
            String price = item.getElementsByClass("p-price").eq(0).text();
            String publish = item.getElementsByClass("p-shopnum").eq(0).text();
            String id = item.getElementsByClass("p-operate").eq(0).select("a").attr("data-sku");
            System.out.println("+++++++++++++++++++++++++++");
            jdGoods.add(new JDGoods(id, img, title, price, publish));
        }
        //返回集合
        return jdGoods;
    }
}
